Forth in Nim

What is it ?

Forth is a stack-oriented programming language.

It is well suited for RPN like so : 2 4 + 6 / returns 1

Why are you bring this up ?

Forth is simple and so a lot of people implement this language in their own language as a fun exercise.

I will try to do the same in Unison.

I finally decided to implement it in Nim!

I plan on documenting the process right here.

The process

Part 0

I will be following this tutorial by Bitsrfr.

Part 1 and 2

[2021-12-12]

I started working on Nirth!

A Forth written in Nim

Those two parts were about reading input, which was not too difficult.

I did not differ too much from the tutorial, except for having the VM be a non-global value.

git

Part 3 and 4

[2021-12-13]

In these parts we added a few basic math operators. Again not too difficult.

In the forth part [ ;) ] things started to get more exciting! We initiated or dictionary of words so we can compile words and reuse them!

part 3 git

part 4 git

Part 5 and 6

[2021-12-14]

In part 5, we searched through our dictionary to find compiled words at run time. Not too difficult. std/strutils from Nim allows us to do so pretty easily. But in part 6, Nim shoots us in the foot. The way the guy from the tutorial implements the processing of compiled words works by having a cyclic definition call where a processInput function might call the runWord function, and the latest calls processInput back. But Nim prevents us from having such cyclic calls by restricting definitions to be written before calls in the file. To hack around this I had to put the definitions of my procs inside other definitions. Kinda like that:

proc i(n: var int) =
  proc r(n: var int) =
      echo("r")
      n -= 1
      if n > 0:
          i(n)

  echo("i")
  n -= 1
  if n > 0:
      e(n)

It ends up looking not very clean. I wish I knew that before settling on Nim to write my Forth.

part 5 git

part 6 git